extends NodeState

@export var zombie: Zombie

func _on_enter() -> void:
	if zombie and zombie.animated_sprite:
		zombie.animated_sprite.play("run")

func _on_physics_process(_delta: float) -> void:
	if not zombie or not zombie.target_player or zombie.is_dead:
		return
	
	# 如果正在受击硬直或击退中，不执行移动
	if zombie.is_hit_stunned or zombie.knockback_timer > 0:
		return
	
	# 获取向玩家移动的方向
	var direction: Vector2 = zombie.get_direction_to_player()
	
	# 设置速度并移动
	zombie.velocity = direction * zombie.move_speed
	zombie.move_and_slide()
	
	# 根据移动方向翻转精灵
	if direction.x < 0:
		zombie.animated_sprite.flip_h = true
	elif direction.x > 0:
		zombie.animated_sprite.flip_h = false

func _on_next_transitions() -> void:
	if not zombie or not zombie.target_player or zombie.is_dead:
		transition.emit("idle")
		return
	
	# 如果僵尸死亡，切换到死亡状态
	if zombie.is_dead:
		transition.emit("die")
		return
	
	var distance: float = zombie.get_distance_to_player()
	
	# 如果玩家在攻击范围内，切换到攻击状态
	if distance <= zombie.attack_range:
		transition.emit("attack")
	# 如果玩家超出检测范围，回到空闲状态
	elif distance > zombie.detection_range:
		transition.emit("idle")

func _on_exit() -> void:
	# 停止移动
	if zombie:
		zombie.velocity = Vector2.ZERO
